package com.swinw.asumall.auth.comtroller;

import com.swinw.asumall.auth.content.SmsContent;
import com.swinw.asumall.auth.feign.MemberFeignService;
import com.swinw.asumall.auth.feign.SmsService;
import com.swinw.asumall.auth.vo.UserRegisterVo;
import com.swinw.common.utils.R;
import com.swinw.common.vo.UserLoginVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Autowired
    SmsService smsService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/login.html")
    public String login(HttpSession session){
        //如果Session中有数据，那么就不能在登录
        Object userLogin = session.getAttribute("userLogin");
        if(userLogin != null){
            //用户已经登录，不能重复登录
            return "redirect:http://swinw.com";
        }else{
            return "login";
        }
    }

    @GetMapping("/register.html")
    public String register(){
        return "register";
    }

    @PostMapping("/userlogin")
    public String userLogin(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        R login = memberFeignService.login(vo);
        int code = (int) login.get("code");
        if(code == 0){//登录成功
            session.setAttribute("userLogin",login.get("user"));
            return "redirect:http://swinw.com";
        }else{
            redirectAttributes.addFlashAttribute("masg","用户名或者密码错误");
            return "redirect:http://auth.swinw.com/login.html";
        }
    }

    /**
     * 获取手机验证码
     * key = auth:phone:cache:号码
     * value = code_time
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
        //1、查询缓存中是否存在当前号码的数据，如果存在且时间还没有过下一次获取验证码的时间，那么就不能从新获取验证码
        String code = stringRedisTemplate.opsForValue().get(SmsContent.PHONE_CACHE_PRE + phone);
        if(!StringUtils.isEmpty(code)){
            String[] split = code.split("_");
            long l = Long.parseLong(split[1]);
            if(System.currentTimeMillis() - l < 60000){//还没有过一个验证码的获取周期，不能获取验证码
                return R.error().put("masg","验证码还在有效期内，不能获取新的验证码！！");
            }else{
                R r = smsService.sendCode(phone);
                //将获取的验证码放入缓存中
                stringRedisTemplate.opsForValue().set(SmsContent.PHONE_CACHE_PRE+phone,
                        (String) r.get("sendCode")+"_"+System.currentTimeMillis(),
                        3,
                        TimeUnit.MINUTES);
                return r;
            }
        }else{
            R r = smsService.sendCode(phone);
            //将获取的验证码放入缓存中
            stringRedisTemplate.opsForValue().set(SmsContent.PHONE_CACHE_PRE+phone,
                    (String) r.get("sendCode")+"_"+System.currentTimeMillis(),
                    3,
                    TimeUnit.MINUTES);
            return r;
        }
    }

    /**
     * 用户注册
     * @return
     */
    @PostMapping(value = "/userRegister",produces = "application/json;charset=UTF-8")
    public String userRegister(@Valid UserRegisterVo vo, BindingResult result,
                               Model model, RedirectAttributes redirectAttributes){
        //1、数据通过JSR303校验，如果校验通不过，就将错误结果回馈到页面
        if (result.hasErrors()){
            //1.1、收集错误信息，将错误信息封装到Map集合中
            List<FieldError> fieldErrors = result.getFieldErrors();
            fieldErrors.forEach(fieldError -> {
                redirectAttributes.addFlashAttribute(fieldError.getField(),fieldError.getDefaultMessage());
            });
            return "redirect:http://auth.swinw.com/register.html";
        }
        //2、校验验证码是否和缓存中的验证码一致
        String s = stringRedisTemplate.opsForValue().get(SmsContent.PHONE_CACHE_PRE + vo.getMobile());
        if(!StringUtils.isEmpty(s)){//提交数据在3分钟以内
            String cacheCode = s.split("_")[0];
            if(cacheCode.equals(vo.getCode())){//如果传递的验证码和缓存中的验证码相等，那么就调用用户添加功能
                //删除验证码
                stringRedisTemplate.delete(SmsContent.PHONE_CACHE_PRE + vo.getMobile());
                R save = memberFeignService.save(vo);
                //添加用户信息
                if(save.get("code").equals("0")){//添加成功
                    return "redirect:/login.html";
                }else{
                    redirectAttributes.addFlashAttribute("username","用户名或者电话号码重复");
                    return "redirect:http://auth.swinw.com/register.html";
                }
            }else{
                redirectAttributes.addFlashAttribute("code","验证码错误");
                return "redirect:http://auth.swinw.com/register.html";
            }
        }
        redirectAttributes.addFlashAttribute("code","验证码过期");
        return "redirect:http://auth.swinw.com/register.html";
    }

}
